//
//  HomeTableViewController.swift
//  weibo
//
//  Created by cmh on 15/8/31.
//  Copyright © 2015年 cmh. All rights reserved.
//

import UIKit
import SVProgressHUD

class HomeTableViewController: BasicTableViewController {

    private lazy var statusListViewModel = StatusListViewModel()
    
    override func viewDidLoad() {
        super.viewDidLoad()
        
        if !UserAccountViewModel.shareUserAccount.userLogon {
            logonView?.laoutAllUI(nil, text: "关注一些人，回这里看看有什么惊喜关注一些人，回这里看看有什么惊喜")
            
            return
        }
        
        // 注册通知
        NSNotificationCenter.defaultCenter().addObserverForName(XMYStatusPictureViewSelectedPhotoNotification, object: nil, queue: nil) { [weak self](notification) in
            
            // 检查通知中的userInfo
            guard let urls = notification.userInfo![XMYStatusPictureViewSelectedPhotoUrlKey] as? [NSURL] else {
                return
            }
            
            guard let indexPath = notification.userInfo![XMYStatusPictureViewSelectedPhotoIndexPathKey] as? NSIndexPath else {
                return
            }
            
            let vc = PhotoBrowserViewController(urls: urls, indexPath: indexPath)
            
            self?.presentViewController(vc, animated: true, completion: nil)
            
        }
        
        prepareTableView()
        
        loadData()

    }
    
    private func prepareTableView() {
    
        // 注册可重用标识
        tableView.registerClass(StatusForwardCell.self, forCellReuseIdentifier: StatusForwardCellID)
        tableView.registerClass(StatusNormalCell.self, forCellReuseIdentifier: StatusNormalCellID)
        // 取消分割线
        tableView.separatorStyle = UITableViewCellSeparatorStyle.None
        
        // 自动处理cell的行高
        tableView.estimatedRowHeight = 100
        
        // 系统的下拉刷新控件
        refreshControl = UIRefreshControl()
        refreshControl?.addTarget(self, action: "loadData", forControlEvents: UIControlEvents.ValueChanged)
        
        // 上拉控件
        tableView.tableFooterView = pullupView
        
    }
    
    func loadData() {
        
        // 开始下拉刷新动画
        refreshControl?.beginRefreshing()
        
        statusListViewModel.loadStatusData(isPullupRefresh: pullupView.isAnimating()).subscribeNext({ (result) -> Void in

            // 展示刷新几条微博的label
            let count = (result as! NSNumber).integerValue
            
            // 下拉提示标签
            self.showPullDownLabel(count)
            
            
            }, error: { (error) -> Void in
                printLog(error)
                
                self.closeAnimating()
                
                SVProgressHUD.showInfoWithStatus("您的网络不给力")
                
            }) {
                
                self.closeAnimating()
                
                self.tableView.reloadData()
        }
    }
    
    // 关闭上拉和下拉刷新动画
    private func closeAnimating() {
    
        // 关闭下拉刷新动画
        self.refreshControl?.endRefreshing()
        // 关闭上拉刷新动画
        self.pullupView.stopAnimating()
        
    
    }
    
    private func showPullDownLabel(count: Int) {
        
        let title = count == 0 ? "没有新微博" : "刷新到 \(count) 条微博"
        let height: CGFloat = 44
        let rect = CGRect(x: 0, y: -2 * height, width: UIScreen.mainScreen().bounds.width, height: height)
        
        pullDownLabel.text = title
        pullDownLabel.frame = rect
        
        UIView.animateWithDuration(1.2, animations: { () -> Void in
            
            self.pullDownLabel.frame = CGRectOffset(self.pullDownLabel.frame, 0, 3 * height)
            
            }) { (_) -> Void in
                UIView.animateWithDuration(1.2) {
                    self.pullDownLabel.frame = rect
                }
        }

    }
    
    // 懒加载下拉展示标签
    private lazy var pullDownLabel: UILabel = {
        
        let label = UILabel(title: nil, color: UIColor.whiteColor(), fontSize: 18)
        
        label.backgroundColor = UIColor.orangeColor()
        label.textAlignment = NSTextAlignment.Center
        
        self.navigationController?.navigationBar.insertSubview(label, atIndex: 0)

        return label
        
    }()
   
    // 懒加载上拉刷新视图
    private lazy var pullupView: UIActivityIndicatorView = {
        
        let pull = UIActivityIndicatorView(activityIndicatorStyle: UIActivityIndicatorViewStyle.WhiteLarge)
        
        pull.color = UIColor.darkGrayColor()
        
        return pull
        
    }()
    
}

// 类似分类
extension HomeTableViewController {
    
    // MARK: - Table view data source
    
    override func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {

        return statusListViewModel.statuses.count
    }
    
    
    override func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
        
        let viewModel = statusListViewModel.statuses[indexPath.item]

        let cell = tableView.dequeueReusableCellWithIdentifier(viewModel.cellID, forIndexPath: indexPath) as! StatusCell
        
         cell.statusRowViewModel = viewModel
        
//        printLog("\(indexPath.row) \(statusListViewModel.statuses.count - 1)")
        
        // 判断是不是最后一条微博,是的话就刷新新的微博
        if (indexPath.row == statusListViewModel.statuses.count - 1) && !pullupView.isAnimating() {

            pullupView.startAnimating()
            
            // 开始刷新数据
            loadData()
        }
        
        return cell
    }
    
    // 计算cell的行高
    override func tableView(tableView: UITableView, heightForRowAtIndexPath indexPath: NSIndexPath) -> CGFloat {

        let viewModel = statusListViewModel.statuses[indexPath.item]
        
        // 如果行高大于0就直接返回，不用在计算
        if viewModel.rowHeight > 0 {
            return viewModel.rowHeight
        }

        let cell = tableView.dequeueReusableCellWithIdentifier(viewModel.cellID) as! StatusCell
        
        // 记录行高
        viewModel.rowHeight = cell.rowHeight(viewModel)
        
        return viewModel.rowHeight
 
    }

}
